<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            background-color: black;
        }

        img {
            position: absolute;
            left: 300px;
            top: 300px;
        }
    </style>
</head>

<body>
    <img src="./../img/tankR.gif" alt="" id="tank">

    <script>
        //------- 方法1
        // let tank = document.getElementsByTagName('img')[0];

        // //获取元素原来的坐标
        // let left = parseInt(window.getComputedStyle(tank).left);//300px
        // let up = parseInt(window.getComputedStyle(tank).top);//300px

        // document.onkeydown = (event) => {

        //     if (event.key == 'ArrowLeft') {
        //         left -= 3;
        //         //把坦克的图片路径换成向左的
        //         tank.src = `./../img/tankL.gif`;
        //         //坦克向左移动
        //         tank.style.left = left + 'px'
        //     } else if (event.key == 'ArrowUp') {
        //         //把坦克的图片路径换成向上的
        //         tank.src = `./../img/tankU.gif`;
        //         up-=3;
        //          //坦克向左移动
        //          tank.style.top = up + 'px'
        //     }
        // }


        // ----- 方法2
        let tank = {
            dom: document.getElementById('tank'),
            left: 300,
            top: 300,
            direction: 'R',//L  U  D
            show() {
                this.dom.src = './../img/tank' + this.direction + '.gif'
                this.dom.style.left = this.left + 'px'
                this.dom.style.top = this.top + 'px'
            }
        }

        document.onkeydown = function (event) {
            if (event.key === 'ArrowLeft') {
                tank.direction = 'L';
                tank.left -= 3;
            } else if (event.key === 'ArrowRight') {
                tank.direction = 'R';
                tank.left += 3;
            } else if (event.key === 'ArrowUp') {
                tank.direction = 'U';
                tank.top -= 3;
            } else if (event.key === 'ArrowDown') {
                tank.direction = 'D';
                tank.top += 3;
            }
            tank.show()
        }



    </script>

</body>

</html>